<template>
  <section class="bw-layout-container">
    <BwHeader
      :saveLoading="saveLoading"
      :previewLoading="previewLoading"
      :renderLoading="renderLoading"
      @save="onSaveDesignInfo"
      @preview="onSaveDesignPreview"
      @save-render="onSaveRenderInfo"
    />

    <section class="bw-layout-content">
      <RouterView>
        <template #default="{ Component }">
          <keep-alive>
            <component :is="Component" :key="route.fullPath" />
          </keep-alive>
        </template>
      </RouterView>
    </section>
  </section>
</template>

<script lang="ts" setup>
import { ref, computed, provide } from 'vue'
import { useRoute } from 'vue-router'
import { setTimeoutUtil } from '@/utils/public'
import {
  saveComDesignInfo,
  saveCustomComRenderInfo,
  useComDesignStoreWithOut,
} from '@/store'

import BwHeader from './header/index.vue'

const route = useRoute()
const saveLoading = ref<boolean>(false)
const renderLoading = ref<boolean>(false)
const previewLoading = ref<boolean>(false)

const designStore = useComDesignStoreWithOut()

/** 保存设计信息 */
const onSaveDesignInfo = () => {
  saveLoading.value = true

  setTimeoutUtil(500, () => {
    const appId = route.params.appId ?? ''
    const pageId = route.params.pageId ?? ''
    const designInfo = designStore.curDesignInfo
    saveComDesignInfo(appId.toString(), pageId.toString(), designInfo).finally(
      () => (saveLoading.value = false)
    )
  })
}

/** 预览设计组件 */
const onSaveDesignPreview = () => {
  previewLoading.value = true
}

/** 保存渲染信息 */
const onSaveRenderInfo = () => {
  renderLoading.value = true

  setTimeoutUtil(500, () => {
    const appId = route.params.appId ?? ''
    const pageId = route.params.pageId ?? ''
    const designInfo = designStore.curDesignInfo
    saveCustomComRenderInfo(
      appId.toString(),
      pageId.toString(),
      designInfo
    ).finally(() => (renderLoading.value = false))
  })
}

provide(
  'previewState',
  computed(() => previewLoading.value)
)
provide('setPreviewState', (value: boolean) => {
  console.log('setPreviewState', value)

  previewLoading.value = value
})
</script>

<style lang="less" scoped>
.bw-layout-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;

  .bw-layout-content {
    width: 100vw;
    height: calc(100vh - 48px);
    overflow: auto;
  }
}
</style>
